package com.atguigu.eduorder.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.Result;
import com.atguigu.eduorder.entity.Order;
import com.atguigu.eduorder.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author zr
 * @since 2021-11-25
 */
@RestController
@RequestMapping("/edu/order/order")
//@CrossOrigin
@Api(tags = "订单管理")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @ApiOperation("查询订单表中的订单状态")
    @GetMapping("isBuyCourse/{memberId}/{courseId}")
    public boolean isBuyCourse(
            @ApiParam(value = "课程Id", name = "courseId", required = true)
            @PathVariable String memberId
            ,
            @ApiParam(value = "课程Id", name = "courseId", required = true)
            @PathVariable String courseId) {
        // 根据课程Id和用户Id  以及订单的支付状态来查询
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId);
        queryWrapper.eq("course_id", courseId);
        // 1表示已经购买
        queryWrapper.eq("status", 1);
        int count = orderService.count(queryWrapper);
        return count > 0;
    }

    @ApiOperation("生成订单")
    @PostMapping("createOrder/{courseId}")
    public Result saveOrder(
            @ApiParam(value = "课程Id", name = "courseId", required = true)
            @PathVariable String courseId, HttpServletRequest request) {
        // 根据token返回会员Id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        // 判断是否登录
        if (StringUtils.isEmpty(memberId)) {
            return Result.fail().message("请登录");
        }
        // 创建订单 返回订单号
        String orderNo = orderService.saveOrder(courseId, memberId);
        Map<String, String> map = new HashMap<>();
        ;
        map.put("orderNo", orderNo);
        return Result.ok(map);
    }

    @ApiOperation("根据订单号查询订单信息")
    @GetMapping("getOrderInfo/{orderNo}")
    public Result getOrderInfo(@PathVariable String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        Order order = orderService.getOne(queryWrapper);
        return Result.ok(order);
    }
}

